package com.cinema.controller;

import com.cinema.model.User;
import com.cinema.model.UserType;
import com.cinema.service.UserService;
import com.cinema.util.InputUtil;
import com.cinema.util.LogUtil;
import com.cinema.util.SimpleFileUtil;
import com.cinema.util.StringUtil;

import java.io.File;
import java.util.List;

/**
 * 管理员控制器
 * 处理管理员相关的所有操作
 */
public class AdminController {
    private final UserService userService;
    
    public AdminController(UserService userService) {
        this.userService = userService;
    }
    
    /**
     * 显示管理员主菜单
     */
    public void showAdminMenu() {
        while (true) {
            try {
                InputUtil.clearScreen();
                InputUtil.printTitle("万东影院管理系统 - 管理员操作菜单");
                
                System.out.println("当前用户: " + userService.getCurrentUser().getUsername() + " (管理员)");
                System.out.println();
                System.out.println("1. 密码管理");
                System.out.println("2. 用户管理");
                System.out.println("3. 查看日志");
                System.out.println("4. 系统统计");
                System.out.println("0. 退出登录");
                
                InputUtil.printSeparator();
                
                int choice = InputUtil.readInt("请选择操作: ", 0, 4);
                
                switch (choice) {
                    case 1:
                        showPasswordManagementMenu();
                        break;
                    case 2:
                        showUserManagementMenu();
                        break;
                    case 3:
                        showLogMenu();
                        break;
                    case 4:
                        showSystemStatistics();
                        break;
                    case 0:
                        if (InputUtil.readConfirmation("确定要退出登录吗？")) {
                            return;
                        }
                        break;
                }
            } catch (Exception e) {
                System.out.println("操作出现错误: " + e.getMessage());
                InputUtil.pauseForUser();
            }
        }
    }
    
    /**
     * 密码管理菜单
     */
    private void showPasswordManagementMenu() {
        while (true) {
            try {
                InputUtil.clearScreen();
                InputUtil.printTitle("密码管理");
                
                System.out.println("1. 修改自身密码");
                System.out.println("2. 重置用户密码");
                System.out.println("0. 返回上级菜单");
                
                InputUtil.printSeparator();
                
                int choice = InputUtil.readInt("请选择操作: ", 0, 2);
                
                switch (choice) {
                    case 1:
                        changeOwnPassword();
                        break;
                    case 2:
                        resetUserPassword();
                        break;
                    case 0:
                        return;
                }
            } catch (Exception e) {
                System.out.println("操作出现错误: " + e.getMessage());
                InputUtil.pauseForUser();
            }
        }
    }
    
    /**
     * 修改自身密码
     */
    private void changeOwnPassword() {
        InputUtil.printTitle("修改自身密码");
        
        String oldPassword = InputUtil.readPassword("请输入当前密码: ");
        String newPassword = InputUtil.readPasswordWithConfirmation("请输入新密码: ");
        
        if (userService.changeCurrentUserPassword(oldPassword, newPassword)) {
            System.out.println("密码修改成功！");
        } else {
            System.out.println("密码修改失败！请检查当前密码是否正确。");
        }
        
        InputUtil.pauseForUser();
    }
    
    /**
     * 重置用户密码
     */
    private void resetUserPassword() {
        InputUtil.printTitle("重置用户密码");
        
        // 显示所有非管理员用户
        List<User> users = userService.getAllUsers();
        if (users == null || users.isEmpty()) {
            System.out.println("没有找到用户信息。");
            InputUtil.pauseForUser();
            return;
        }
        
        System.out.println("可重置密码的用户列表：");
        System.out.println(StringUtil.repeat("-", 80));
        for (User user : users) {
            if (user.getUserType() != UserType.ADMIN || !user.getUsername().equals("admin")) {
                System.out.println(userService.formatUserInfo(user));
            }
        }
        System.out.println(StringUtil.repeat("-", 80));
        
        String targetUserId = InputUtil.readNonEmptyString("请输入要重置密码的用户ID: ");
        User targetUser = userService.findUserById(targetUserId);
        
        if (targetUser == null) {
            System.out.println("用户不存在！");
            InputUtil.pauseForUser();
            return;
        }
        
        if (targetUser.getUsername().equals("admin")) {
            System.out.println("不能重置admin管理员账户的密码！");
            InputUtil.pauseForUser();
            return;
        }
        
        System.out.println("将要重置以下用户的密码:");
        System.out.println(userService.formatUserInfo(targetUser));
        
        if (InputUtil.readConfirmation("确定要重置该用户的密码为123456吗？")) {
            if (userService.resetUserPassword(targetUserId)) {
                System.out.println("密码重置成功！新密码为: 123456");
                System.out.println("用户下次登录时需要修改密码。");
            } else {
                System.out.println("密码重置失败！");
            }
        }
        
        InputUtil.pauseForUser();
    }
    
    /**
     * 用户管理菜单
     */
    private void showUserManagementMenu() {
        while (true) {
            try {
                InputUtil.clearScreen();
                InputUtil.printTitle("用户管理");
                
                System.out.println("1. 查看所有用户");
                System.out.println("2. 添加用户");
                System.out.println("3. 修改用户信息");
                System.out.println("4. 删除用户");
                System.out.println("5. 搜索用户");
                System.out.println("0. 返回上级菜单");
                
                InputUtil.printSeparator();
                
                int choice = InputUtil.readInt("请选择操作: ", 0, 5);
                
                switch (choice) {
                    case 1:
                        viewAllUsers();
                        break;
                    case 2:
                        addUser();
                        break;
                    case 3:
                        modifyUser();
                        break;
                    case 4:
                        deleteUser();
                        break;
                    case 5:
                        searchUsers();
                        break;
                    case 0:
                        return;
                }
            } catch (Exception e) {
                System.out.println("操作出现错误: " + e.getMessage());
                InputUtil.pauseForUser();
            }
        }
    }
    
    /**
     * 查看所有用户
     */
    private void viewAllUsers() {
        InputUtil.printTitle("所有用户信息");
        
        List<User> users = userService.getAllUsers();
        if (users == null || users.isEmpty()) {
            System.out.println("没有用户信息。");
        } else {
            System.out.println(StringUtil.repeat("-", 120));
            for (User user : users) {
                System.out.println(userService.formatUserInfo(user));
            }
            System.out.println(StringUtil.repeat("-", 120));
            System.out.println("总计: " + users.size() + " 个用户");
        }
        
        InputUtil.pauseForUser();
    }
    
    /**
     * 添加用户
     */
    private void addUser() {
        InputUtil.printTitle("添加用户");
        
        try {
            String username = InputUtil.readUsername("请输入用户名: ");
            
            if (userService.isUsernameExists(username)) {
                System.out.println("用户名已存在！");
                InputUtil.pauseForUser();
                return;
            }
            
            String phoneNumber = InputUtil.readPhoneNumber("请输入手机号: ");
            
            if (userService.isPhoneNumberExists(phoneNumber)) {
                System.out.println("手机号已存在！");
                InputUtil.pauseForUser();
                return;
            }
            
            System.out.println("请选择用户类型:");
            System.out.println("1. 管理员");
            System.out.println("2. 经理");
            System.out.println("3. 用户");
            
            int typeChoice = InputUtil.readInt("请选择用户类型: ", 1, 3);
            UserType userType;
            switch (typeChoice) {
                case 1:
                    userType = UserType.ADMIN;
                    break;
                case 2:
                    userType = UserType.MANAGER;
                    break;
                case 3:
                    userType = UserType.USER;
                    break;
                default:
                    System.out.println("无效的用户类型！");
                    InputUtil.pauseForUser();
                    return;
            }
            
            System.out.println("\n将要添加的用户信息:");
            System.out.println("用户名: " + username);
            System.out.println("手机号: " + phoneNumber);
            System.out.println("用户类型: " + userType.getDescription());
            System.out.println("默认密码: 123456");
            
            if (InputUtil.readConfirmation("确定要添加该用户吗？")) {
                if (userService.addUser(username, phoneNumber, userType)) {
                    System.out.println("用户添加成功！");
                    System.out.println("默认密码为: 123456");
                    System.out.println("用户首次登录时需要修改密码。");
                } else {
                    System.out.println("用户添加失败！");
                }
            }
            
        } catch (Exception e) {
            System.out.println("添加用户时发生错误: " + e.getMessage());
        }
        
        InputUtil.pauseForUser();
    }
    
    /**
     * 修改用户信息
     */
    private void modifyUser() {
        InputUtil.printTitle("修改用户信息");
        
        String userId = InputUtil.readNonEmptyString("请输入要修改的用户ID: ");
        User user = userService.findUserById(userId);
        
        if (user == null) {
            System.out.println("用户不存在！");
            InputUtil.pauseForUser();
            return;
        }
        
        if (user.getUsername().equals("admin")) {
            System.out.println("不能修改admin管理员账户的信息！");
            InputUtil.pauseForUser();
            return;
        }
        
        System.out.println("当前用户信息:");
        System.out.println(userService.formatUserInfo(user));
        System.out.println("\n注意: 只能修改用户类型和手机号，用户名和用户ID不可修改。");
        
        try {
            String newPhoneNumber = InputUtil.readString("请输入新手机号（回车保持不变）: ", user.getPhoneNumber());
            
            if (!newPhoneNumber.equals(user.getPhoneNumber()) && userService.isPhoneNumberExists(newPhoneNumber)) {
                System.out.println("手机号已存在！");
                InputUtil.pauseForUser();
                return;
            }
            
            System.out.println("请选择新的用户类型:");
            System.out.println("1. 管理员");
            System.out.println("2. 经理");
            System.out.println("3. 用户");
            System.out.println("当前类型: " + user.getUserType().getDescription());
            
            int currentTypeIndex = user.getUserType() == UserType.ADMIN ? 1 : 
                                  user.getUserType() == UserType.MANAGER ? 2 : 3;
            int typeChoice = InputUtil.readInt("请选择用户类型（回车保持不变）: ", currentTypeIndex, 1, 3);
            
            if (typeChoice == 0) {
                typeChoice = currentTypeIndex;
            }
            
            UserType newUserType;
            switch (typeChoice) {
                case 1:
                    newUserType = UserType.ADMIN;
                    break;
                case 2:
                    newUserType = UserType.MANAGER;
                    break;
                case 3:
                    newUserType = UserType.USER;
                    break;
                default:
                    newUserType = user.getUserType();
            }
            
            if (InputUtil.readConfirmation("确定要保存修改吗？")) {
                if (userService.updateUser(userId, newPhoneNumber, newUserType)) {
                    System.out.println("用户信息修改成功！");
                } else {
                    System.out.println("用户信息修改失败！");
                }
            }
            
        } catch (Exception e) {
            System.out.println("修改用户信息时发生错误: " + e.getMessage());
        }
        
        InputUtil.pauseForUser();
    }
    
    /**
     * 删除用户
     */
    private void deleteUser() {
        InputUtil.printTitle("删除用户");
        
        String userId = InputUtil.readNonEmptyString("请输入要删除的用户ID: ");
        User user = userService.findUserById(userId);
        
        if (user == null) {
            System.out.println("用户不存在！");
            InputUtil.pauseForUser();
            return;
        }
        
        if (user.getUsername().equals("admin")) {
            System.out.println("不能删除admin管理员账户！");
            InputUtil.pauseForUser();
            return;
        }
        
        System.out.println("将要删除的用户信息:");
        System.out.println(userService.formatUserInfo(user));
        
        System.out.println("\n警告: 删除用户后将无法恢复，请谨慎操作！");
        
        if (InputUtil.readConfirmation("确定要删除该用户吗？")) {
            if (userService.deleteUser(userId)) {
                System.out.println("用户删除成功！");
            } else {
                System.out.println("用户删除失败！");
            }
        }
        
        InputUtil.pauseForUser();
    }
    
    /**
     * 搜索用户
     */
    private void searchUsers() {
        InputUtil.printTitle("搜索用户");
        
        String keyword = InputUtil.readNonEmptyString("请输入搜索关键词（用户ID/用户名/手机号）: ");
        List<User> results = userService.searchUsers(keyword);
        
        if (results == null || results.isEmpty()) {
            System.out.println("没有找到匹配的用户。");
        } else {
            System.out.println("搜索结果：");
            System.out.println(StringUtil.repeat("-", 120));
            for (User user : results) {
                System.out.println(userService.formatUserInfo(user));
            }
            System.out.println(StringUtil.repeat("-", 120));
            System.out.println("找到 " + results.size() + " 个用户");
        }
        
        InputUtil.pauseForUser();
    }
    
    /**
     * 查看日志菜单
     */
    private void showLogMenu() {
        while (true) {
            try {
                InputUtil.clearScreen();
                InputUtil.printTitle("日志查看");
                
                System.out.println("1. 查看今日日志");
                System.out.println("2. 查看指定日期日志");
                System.out.println("3. 清理旧日志");
                System.out.println("0. 返回上级菜单");
                
                InputUtil.printSeparator();
                
                int choice = InputUtil.readInt("请选择操作: ", 0, 3);
                
                switch (choice) {
                    case 1:
                        viewTodayLog();
                        break;
                    case 2:
                        viewLogByDate();
                        break;
                    case 3:
                        cleanOldLogs();
                        break;
                    case 0:
                        return;
                }
            } catch (Exception e) {
                System.out.println("操作出现错误: " + e.getMessage());
                InputUtil.pauseForUser();
            }
        }
    }
    
    /**
     * 查看今日日志
     */
    private void viewTodayLog() {
        InputUtil.printTitle("今日系统日志");
        
        String log = LogUtil.readTodayLog();
        if (log == null || log.trim().isEmpty()) {
            System.out.println("今日暂无日志记录。");
        } else {
            System.out.println(log);
        }
        
        InputUtil.pauseForUser();
    }
    
    /**
     * 查看指定日期日志
     */
    private void viewLogByDate() {
        InputUtil.printTitle("查看指定日期日志");
        
        String date = InputUtil.readNonEmptyString("请输入日期（格式：yyyy-MM-dd）: ");
        String log = LogUtil.readLogByDate(date);
        
        if (log == null || log.trim().isEmpty()) {
            System.out.println("指定日期无日志记录。");
        } else {
            System.out.println(log);
        }
        
        InputUtil.pauseForUser();
    }
    
    /**
     * 清理旧日志
     */
    private void cleanOldLogs() {
        InputUtil.printTitle("清理旧日志");
        
        System.out.println("当前日志文件:");
        String[] logFiles = LogUtil.getLogFileList();
        if (logFiles.length == 0) {
            System.out.println("没有日志文件。");
            InputUtil.pauseForUser();
            return;
        }
        
        for (String file : logFiles) {
            System.out.println("- " + file);
        }
        
        System.out.println("\n注意: 将删除30天前的旧日志文件。");
        
        if (InputUtil.readConfirmation("确定要清理旧日志吗？")) {
            LogUtil.cleanOldLogs();
            System.out.println("旧日志清理完成！");
        }
        
        InputUtil.pauseForUser();
    }
    
    /**
     * 显示系统统计信息
     */
    private void showSystemStatistics() {
        InputUtil.printTitle("系统统计信息");
        
        System.out.println(userService.getUserStatistics());
        System.out.println();
        
        System.out.println("数据文件统计:");
        String[] dataFiles = listDataFiles();
        for (String file : dataFiles) {
            long size = getFileSize(file);
            System.out.printf("- %s: %d 字节%n", file, size);
        }
        
        System.out.println("\n日志文件统计:");
        String[] logFiles = LogUtil.getLogFileList();
        System.out.println("日志文件数量: " + logFiles.length);
        
        InputUtil.pauseForUser();
    }

    private String[] listDataFiles() {
        File dataDir = new File("data");
        if (!dataDir.exists() || !dataDir.isDirectory()) {
            return new String[0];
        }
        File[] files = dataDir.listFiles((dir, name) -> name.endsWith(".txt"));
        if (files == null) {
            return new String[0];
        }
        String[] fileNames = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            fileNames[i] = files[i].getName();
        }
        return fileNames;
    }

    private long getFileSize(String fileName) {
        File file = new File("data", fileName);
        return file.exists() ? file.length() : 0;
    }
}